package com.chenyi.data.structure.sparsearray;

/**
 * @author by chenyi
 * @className SparseArray
 * @date 2021/12/16 17:54
 */

public class SparseArray {

    public static final int ARRAY_LENGTH = 11;

    public static final int SPARES_ARRAY_LENGTH = 3;

    public static void main(String[] args) {
        // 创建二位数组
        int[][] array = new int[ARRAY_LENGTH][ARRAY_LENGTH];

        // 存储的数据
        array[1][2] = 1;
        array[2][3] = 2;
        array[3][3] = 2;

        // 遍历二位数组
        for (int[] ints : array) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }

        // 获取稀疏组长度
        int sum = 0;
        for (int[] ints : array) {
            for (int anInt : ints) {
                if (anInt != 0) {
                    sum++;
                }
            }
        }

        // 创建稀疏数组
        // sum + 1用于存储整个二维数组的长度与有效数据个数
        int[][] sparesArr = new int[sum + 1][SPARES_ARRAY_LENGTH];

        // 存储二维数组的长度信息
        sparesArr[0][0] = ARRAY_LENGTH;
        sparesArr[0][1] = ARRAY_LENGTH;
        sparesArr[0][2] = sum;

        // 将二维数组中的数据存储到稀疏数组中
        int count = 0;
        for (int i = 0; i < ARRAY_LENGTH; i++) {
            for (int j = 0; j < ARRAY_LENGTH; j++) {
                if (array[i][j] != 0) {
                    count++;
                    sparesArr[count][0] = i;
                    sparesArr[count][1] = j;
                    sparesArr[count][2] = array[i][j];
                }
            }
        }

        // 输出稀疏数组
        System.out.println("================================");
        for (int i = 0; i < sparesArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparesArr[i][0], sparesArr[i][1], sparesArr[i][2]);
        }

        // 稀疏数组转二维数组
        int[][] newArray = new int[sparesArr[0][0]][sparesArr[0][1]];

        // 将数据存储到二维数组中
        for (int i = 0; i < sparesArr.length; i++) {
            if (i != 0) {
                newArray[sparesArr[i][0]][sparesArr[i][1]] = sparesArr[i][2];
            }
        }

        System.out.println("========================");
        for (int[] ints : newArray) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
    }

}
